package com.young.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;

/**
 * POJO工具
 *
 * @author ：<a href="mailto:youngkun2016@163.com">young</a>
 * @date ：Created in 2020/7/5
 */
public class BeanUtils {
    private static Logger logger = LogManager.getLogger(CollectionsUtils.class);
    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 从类实例中copy属性值
     * 并返回一个指定类的实例作为返回值
     * 基于{@link ObjectMapper}进行序列化与反序列化
     * @param source
     * @param type
     * @param <T>
     * @return
     * @throws IOException
     */
    public static <T, E> T copyProperties(E source, Class<T> type) {
        String jsonString = null;
        try {
            jsonString = objectMapper.writeValueAsString(source);
            return objectMapper.readValue(jsonString, type);
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage(),e);
            throw new RuntimeException();
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
            throw new RuntimeException();
        }
    }
}
